<template>
  <div class="wrap">
    <pro-table
      ref="proTableInst"
      tableTitle="用户列表"
      :columns="columns"
      :request="fetchUserPage"
      auto-height
    >
      <template #operation>
        <n-space>
          <n-button type="primary" @click="handleAddUser">新增用户</n-button>
        </n-space>
      </template>
    </pro-table>

    <n-drawer
      v-model:show="drawerShow"
      :width="900"
      resizable
      :maskClosable="false"
      @after-leave="resetForm"
    >
      <n-drawer-content closable :loading="true" :title="handleTag">
        <pro-form
          ref="userFormInst"
          v-model:form="userForm"
          :options="userFormOptions"
          :formProps="{
            labelPlacement: 'left',
            labelWidth: 100
          }"
        ></pro-form>

        <template #footer>
          <n-space>
            <n-button @click="drawerShow = false">取消</n-button>
            <n-button type="primary" @click="userConfirm">确认</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>

    <pro-modal
      v-model:show="updatePwdModal"
      title="修改密码"
      :maxHeight="500"
      :loading="updatePwdModalLoading"
      :mask-closable="false"
      @afterLeave="resetPasswordForm"
      @ok="handleUserPasswordEditCommit"
    >
      <NForm
        ref="updatePwdFormInst"
        labelPlacement="left"
        labelWidth="auto"
        style="margin-top: 20px"
        :model="passwordForm"
      >
        <NFormItem
          label="新密码"
          :rule="{
            required: true,
            trigger: 'blur',
            validator: passwordValidator
          }"
          path="newPassword"
        >
          <NInput
            v-model:value="passwordForm.newPassword"
            placeholder="请输入新密码"
          />
        </NFormItem>
      </NForm>
    </pro-modal>

    <pro-modal
      v-model:show="editRoleModal"
      title="授予角色"
      :maxHeight="500"
      :loading="editRoleModalLoading"
      :mask-closable="false"
      @afterLeave="handleRoleModalAfterLeave"
      @ok="handleUserRoleEditCommit"
    >
      <n-select
        v-model:value="currentUserRole"
        :options="roleOptions"
        placeholder="请选择角色"
        filterable
      ></n-select>
    </pro-modal>
  </div>
</template>

<script lang="ts" setup name="UserList">
  import { ProTableInst } from '@/components/pro-table/type'
  import { ProFormInst } from '@/components/pro-form/type'
  import { useUserApi, useUserProForm, useUserProTable } from './hooks'
  import { FormInst } from 'naive-ui'
  import { passwordValidator } from '@/utils/validator'

  const proTableInst = ref<ProTableInst | null>(null)
  const userFormInst = ref<ProFormInst | null>(null)
  const updatePwdFormInst = ref<FormInst | null>(null)

  const drawerShow = ref(false)
  const handleType = ref<'add' | 'edit' | ''>('')
  const handleTag = computed(() =>
    handleType.value === 'add' ? '新增用户' : '修改用户'
  )

  const updatePwdModal = ref(false)
  const [passwordForm, resetPasswordForm] = useProRef({
    newPassword: ''
  })
  const { orgOptions } = useGetOrgList()

  const roleOptions = ref([])

  const currentUser = ref<any>({})
  const currentUserRole = ref('')
  const editRoleModal = ref(false)

  const { userForm, resetForm, userFormOptions } = useUserProForm({
    handleType,
    orgOptions
  })

  const handleAddUser = () => {
    handleType.value = 'add'
    drawerShow.value = true
  }

  const handleEditUser = (row) => {
    userForm.value = row
    handleType.value = 'edit'
    drawerShow.value = true
  }

  const handleEditUserRole = (row) => {
    currentUser.value = row
    currentUserRole.value = row.roleCode
    editRoleModal.value = true
  }

  const handleSetNewPwd = (row) => {
    currentUser.value = row
    updatePwdModal.value = true
  }

  const handleRoleModalAfterLeave = () => {
    currentUser.value = {}
    currentUserRole.value = ''
  }

  const userConfirm = async () => {
    if (await userFormInst.value?.handleSubmit()) {
      fetchAddOrEditUser()
    }
  }

  const handleUserRoleEditCommit = () => {
    const data = {
      id: currentUser.value.userId,
      roleCode: currentUserRole.value
    }
    fetchEditUserRole(data, () => {
      editRoleModal.value = false
    })
  }

  const handleUserPasswordEditCommit = async () => {
    await updatePwdFormInst.value?.validate()
    const data = {
      id: currentUser.value.id,
      password: passwordForm.value.newPassword
    }
    fetchEditUserPassword(data, () => {
      updatePwdModal.value = false
    })
  }

  const {
    fetchUserPage,
    fetchAddOrEditUser,
    fetchDelUser,
    changeUserStatus,
    fetchEditUserRole,
    fetchEditUserPassword,
    editRoleModalLoading,
    userStatusLoading,
    updatePwdModalLoading
  } = useUserApi({
    handleType,
    handleTag,
    drawerShow,
    userForm,
    proTableInst,
    orgOptions,
    roleOptions,
    currentUserRole
  })

  const { columns } = useUserProTable({
    handleEditUser,
    fetchDelUser,
    changeUserStatus,
    handleSetNewPwd,
    handleEditUserRole,
    orgOptions,
    userStatusLoading
  })
</script>

<style lang="less" scoped></style>
